var SUCCESS_CODE = 200,
	TOKEN_EXPIRED = 401,
	
	//测试环境
//	API_URL = "http://118.190.115.42/",
//	SSO_URL = API_URL+"sso/",
//	BUSINESS_URL = API_URL + "busi/";
//	FILE_URL = "http://118.190.115.42:5888/file",
//	UPLOAD_FILE_URL=FILE_URL+"/save";
//	ASSESSMENT_URL = API_URL + "evaluate/",
//	SETTLEMENT_URL = API_URL + "sett/";
//	PUBMANAGE_URL  = API_URL + "pub/";
//	COMMISSION_URL = API_URL + "com/";
//	UPLOAD_FILE_ALLOWED_TYPES="jpg,png";
//	FILE_VIEW_URL="http:/118.190.115.42/";
//	
	/*API_URL = "http://127.0.0.1/",
	UPLOAD_FILE_URL=FILE_URL+"/save";
	UPLOAD_FILE_ALLOWED_TYPES="jpg,png";
	FILE_VIEW_URL="http://114.215.16.28:8888/";
	SSO_URL = "http://192.168.1.160:8084/",
	BASE_URL = "http://192.168.1.160:8086/";*/
	SSO_URL = "http://127.0.0.1:8084/",
	FILE_URL = "http://192.168.1.200:5888/file",
	BASE_URL = "http://127.0.0.1:8086/";
/**
 * 获取session用户
 * @returns object
 */
function getSessionUser(){
	var user=null;
	var userStr = getSessionData('user');
	if($.trim(userStr)!=''){
		user = JSON.parse(userStr);
	}
	return user;
}
/**
 * 获取用户权限
 * @returns arrays
 */
function getUserPower(){
	var userPower=[];
	var userStr = getSessionData('userPower');
	if($.trim(userStr)!=''){
		userPower = JSON.parse(userStr);
	}
	return userPower;
}

function checkPower(funid){
	var powers = getUserPower();
	if(powers!=null){
		for(var i=0;i<powers.length;i++){
			if(powers[i].funid==funid){
				return true;
			}
		}
	}
	return false;
}

function checkPowerAndJump(funid){
	if(!checkPower(funid)){
		window.location.href="/403.html";
	}
}
/**
 * 清除session
 * @returns void
 */
function clearSession(){
	if(window.sessionStorage){
		window.sessionStorage.clear(); 
	}else{
		var cookies = document.cookie ? document.cookie.split('; ') : [];
		for (var i = 0, l = cookies.length; i < l; i++) {
			var parts = cookies[i].split('=');
			var name = decodeURIComponent(parts.shift());
			if (name) {
				$.removeCookie(name);
			}
		}
	}
}

/**
 * 存储session数据
 * @param key
 * @param value
 * @returns
 */
function storeSessionData(key,value){
	if(window.sessionStorage ){
		window.sessionStorage.setItem(key, value); 
	}else{
		$.cookie(key,value,{ expires: 7, path: '/' });
	}
}
/**
 * 获取session数据
 * @param key
 * @param value
 * @returns
 */
function getSessionData(key,value){
	var value = '';
    if(window.sessionStorage ){
    	value =  window.sessionStorage.getItem(key);
	}else{
		value =  $.cookie(key);
	}
    if(key=='userToken' && $.trim(value)==''){
    	window.location.href='/login.html';
    }
    return value;
}
	
function checkFileType(fileFiledId){
	 var flag = true;
	 var fileUrl = $("#"+fileFiledId).val();
	 if($.trim(fileUrl)!=''){
		 var fileExtension = fileUrl.split('.').pop().toLowerCase();
		 if((UPLOAD_FILE_ALLOWED_TYPES != '*') &&
			        !UPLOAD_FILE_ALLOWED_TYPES.match(fileExtension)){
			 flag=false;
	     }
	 }
	 return flag;
}
/**
 * 发送单个文件
 * @param fileFiledId 文件域id
 * @param options 其他操作参数
 * @returns
 */
function sendSingleFile(fileFiledId,options){
   var result = {"code":"500","message":"上传文件失败！"};
   var fd=new FormData();  
   fd.append("file",$("#"+fileFiledId).get(0).files[0]);
   if(typeof options=="undefined" || typeof options!='object'){
	   options={};
   }
   if((typeof options.useToken) ==  "undefined" || options.useToken){
	    options['headers'] = {
			 'Authorization': 'Bearer '+getSessionData('userToken')
//			 'Action':'getToken'
	    }
	}
   if((typeof options.dataParams) ==  "object"){
	   $.each(options.dataParams, function(key, val) {
		   fd.append(key,options.dataParams[key]);
		});
   }
   var defaultConfig={  
		      url:UPLOAD_FILE_URL,  
		      type:"POST",  
		      async: false,
		      processData: false,  
		      contentType:false,  
		      dataType:'json',
		      data: fd,  
		      xhr: function() {
		         myXhr = $.ajaxSettings.xhr();
		         if(myXhr.upload){
		            myXhr.upload.addEventListener('progress',function(evt){  
		               var percentComplete = Math.round(evt.loaded*100 / evt.total);  
		            }, false);
		         }  
		         return myXhr;  
		      },  
		      success:function(data){
		    	   result=data;
			    }  
			 }
   $.ajax($.extend({},defaultConfig,options)); 
	return result;
}
	
	   
/**
 * 发送req请求
 * @param req
 * @returns
 */
function ajaxRequest(req){
	var	ajaxConfig = $.extend(true,req.reqJSON,{});
	if(ajaxConfig['type'] == 'post' || ajaxConfig['type'] == 'put'){
		ajaxConfig['contentType'] = 'application/json;charset=utf-8';
	}
	ajaxConfig['error'] = function(data){
		var error = $.parseJSON(data.responseText);
		if(typeof error  == undefined){
			layer.msg('系统异常！',{icon:5});
		}else if(error.code == 401){
			refreshToken('Bearer '+getSessionData('userToken'),req);
		}else{
			layer.msg(error.message,{icon:5});
		}
	};
	ajaxConfig['success'] = function(data){
//		if(data.code == SUCCESS_CODE){
			return req.successFn(data);
//		}
	};
	
	ajaxConfig['beforeSend'] = function(xhr) {
		if((typeof req.useToken) ==  "undefined" || req.useToken){
			xhr.setRequestHeader('Authorization','Bearer '+getSessionData('userToken'));
//			xhr.setRequestHeader('Action','getToken');
		}
	}
	$.ajax(ajaxConfig);
}
function refreshToken(token,req){
	var	ajaxConfig ={};
	ajaxConfig['url'] = API_URL+'accessToken/refresh';
	ajaxConfig['type'] = 'put';
	ajaxConfig['error'] = function(data){
		layer.msg(data.responseText,{icon:5});
	};
	ajaxConfig['success'] = function(data){
		if(data.code == SUCCESS_CODE){
			storeSessionData('userToken',data.data);
			return ajaxRequest(req);
		}
	}
	ajaxConfig['beforeSend'] = function(xhr) {
		xhr.setRequestHeader('Authorization','Bearer '+getSessionData('userToken'));
	}
	$.ajax(ajaxConfig);
}
/**
 * 根据form表单序列化json对象
 * @param form
 * @returns
 */
function serializeForm(form){
	var data = {};
	$(form).serializeArray().map(function(x){
      if (data[x.name] !== undefined) {
                if (!data[x.name].push) {
                    data[x.name] = [data[x.name]];
                }
                data[x.name].push(x.value || '');
            } else {
                data[x.name] = x.value || '';
            }
     });
	return data;
}

/**
 * 获取页面传入的参数
 * @param name
 * @returns
 */
function GetQueryString(name)
{
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}


$(function(){
	//主动检查页面元素
	$.each($(".checkPower"),function(i,obj){
		var key = $(obj).attr("power");
		if(!checkPower(key)){
			$(obj).remove();
		}
	})
})

//时间戳转日期
function timeTransfoDate(time){
	time = parseInt(time);
	var date =  new Date(time);
    var y = 1900+date.getYear();
    var m = "0"+(date.getMonth()+1);
    var d = "0"+date.getDate();
    return y+"-"+m.substring(m.length-2,m.length)+"-"+d.substring(d.length-2,d.length);
}

//时间戳转日期+时间
function timeTransfoTime(time){
	time = parseInt(time);
	var date =  new Date(time);
    var y = 1900+date.getYear();
    var m = "0"+(date.getMonth()+1);
    var d = "0"+date.getDate();
    var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    return y+"-"+m.substring(m.length-2,m.length)+"-"+d.substring(d.length-2,d.length)+" "+hour+":"+minute+":"+second;
}

/**
 * 格式化金额
 */
function formatMoney(s, n)   
{   
   n = n > 0 && n <= 20 ? n : 2;   
   s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";   
   var l = s.split(".")[0].split("").reverse(),   
   r = s.split(".")[1];   
   t = "";   
   for(i = 0; i < l.length; i ++ )   
   {   
      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");   
   }   
   return t.split("").reverse().join("") + "." + r;   
} 
/**
 * 格式化秒 --》 分:秒
 */
function formatTime(t) {
    return Math.floor(t/60)+":"+(t%60/100).toFixed(2).slice(-2)+"分";
}
/**
 * 通过凭证ID获取图片路径 并改变图片路径（仅Table内使用）
 */
function getURLById(id,waterVoucherId){
	var req = {};
	req['reqJSON'] = {
		type:"get",
		url:FILE_URL+"/getById?id="+id
	};
	req['useToken'] = true;
	req['async'] = false;
	req['successFn'] = function(respData){
		$('#'+waterVoucherId).attr('src',FILE_VIEW_URL + respData.data);
	};
	ajaxRequest(req);
}